{% extends '_charge.html' %}
{% import 'public.html' as public %}


{% block main_contain %}
<div id="CarParkPreview">
    <div class="row">
        <div v-for="place in Places" class="col-md-2 col-sm-6 col-12">
            <div class="info-box">
            <span :class="['info-box-icon', place.ValidCount>0?'bg-success':'bg-danger']">
                <i :class="['fas',place.VehicleType=='Car'?'fa-car':'fa-motorcycle']" style="font-size: 50px;"></i>
            </span>
            <div class="info-box-content text-center">
                <span class="info-box-text" style="font-size: larger;font-weight: bold;">
                    {[ColumnName[place.ParkingType]+ColumnName[place.VehicleType]]}：{[place.Provide]}
                </span>
                <span class="info-box-text" style="font-size: larger;font-weight: bold;">
                    剩餘車位數：{[ place.ValidCount ]}
                </span>
            </div>
            <!-- /.info-box-content -->
            </div>
            <!-- /.info-box -->
        </div>
        <!-- /.col -->
    </div>
    <div class="row">
        <div v-for="lane in Lanes" class="col-lg-6">
            <div :class="['card',lane_event_bg(lane.LicensePlate)]">
                <div class="card-header">
                    <div class="text-center">
                        <span v-if="lane.GateName==''" style="font-size: x-large">{[ColumnName[lane.GateType]]}準備</span>
                        <div v-else class="row justify-content-between">
                            <span style="font-size: x-large;">{[ lane.GateName ]}：{[ColumnName[lane.VehicleType]]}</span>
                            <span style="font-size: x-large;">車牌結果：<b>{[ lane.LicensePlate ]}</b></span>
                            <span style="font-size: x-large;">識別時間：{[ lane.GateTime ]}</span>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="form-group row justify-content-center">
                        <img :src="lane.LicensePlateImg==''?'{{url_for('static', filename='images/default/vehicle.jpg')}}':lane.LicensePlateImg" 
                        class="img-thumbnail" style="width: 94%;">
                    </div>
                    <div class="row">
                        <div v-for="item in GateKeys" class="col-sm-6">
                            <div v-for="k in item" class="input-group mb-3 text-center">
                                <div class="input-group-prepend">
                                  <span class="input-group-text">{[ ColumnName[k] ]}</span>
                                </div>
                                <input v-if="k=='VehicleType'" :value="lane[k]==''?'沒有車輛':ColumnName[lane[k]]" type="text" class="form-control" readonly>
                                <input v-else-if="k=='ParkingType'" :value="ColumnName[lane[k]]" type="text" class="form-control" readonly>
                                <input v-else v-model="lane[k]" type="text" class="form-control" readonly>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer text-center">
                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#GateBarModal" style="font-size: larger;" 
                    @click="gatebar_control(lane.GateType)">
                        <i class="fas fa-arrow-up"></i> 起杆
                    </button>
                </div>
            </div>
        </div>
    </div>
    <!--起杆对话框-->
    <div class="modal fade" id="GateBarModal" data-backdrop="static" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
            <div class="modal-header justify-content-center">
                <h4 class="modal-title text-danger"><i class="fas fa-exclamation-triangle"></i> 閘機起杆控制</h4>
            </div>
            <div class="modal-body text-center">
                <div v-for="(val, key) in GateBarData" v-if="key!='GateType'" 
                class="form-group row" style="font-size: large;">
                    <label class="col-sm-4 col-form-label">{[ ColumnName[key] ]}：</label>
                    <div class="col-sm-8">
                        <select v-if="key=='GateID'" v-model="GateBarData[key]" class="form-control" :name="key">
                            {% if ValidGates %}
                            {% for gate in ValidGates %}
                            <option value="{{gate['GateID']}}">{{gate['GateName']}}</option>
                            {% endfor %}
                            {% endif %}
                        </select>
                        <select v-else-if="key=='VehicleType'" v-model="GateBarData[key]" class="form-control" :name="key">
                          {% for k, v in VehicleTypes.items() %}
                          <option value="{{ k }}">{{ v }}</option>
                          {% endfor %}
                        </select>
                        <select v-else-if="key=='UpBarMethod'" v-model="GateBarData[key]" class="form-control" :name="key">
                            {% for k, v in UpBarMethods.items() %}
                            <option value="{{ k }}">{{ v }}</option>
                            {% endfor %}
                        </select>
                        <input v-else-if="key=='LicensePlate'" v-model="GateBarData[key]" class="form-control" :type="'text'" :name="key"
                        :readonly="GateBarData.UpBarMethod!='LicensePlate'?'readonly':false" style="text-transform: uppercase;">
                    </div>
                </div>
            </div>
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-success" @click="send_gate_upbar">確認</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
            </div>
            <!-- /.modal-content -->
        </div>
      <!-- /.modal-dialog -->
      </div>
</div>
{% endblock %}


{% block scripts %}
{{ super() }}
<script>
    // 车场预览
    var CarParkPreview = new Vue({
        el: '#CarParkPreview',
        delimiters: ['{[', ']}'],
        data: {
            Places:[
                {ParkingType:'Hourly',VehicleType:'Car',Provide:0,ValidCount:0},
                {ParkingType:'Hourly',VehicleType:'Moto',Provide:0,ValidCount:0},
                {ParkingType:'Monthly',VehicleType:'Car',Provide:0,ValidCount:0},
                {ParkingType:'Monthly',VehicleType:'Moto',Provide:0,ValidCount:0},
                {ParkingType:'Private',VehicleType:'Car',Provide:0,ValidCount:0},
                {ParkingType:'Private',VehicleType:'Moto',Provide:0,ValidCount:0},
            ],
            Lanes:[
                {
                    GateType:'Entrance',
                    GateID:'',
                    GateName:'',
                    LicensePlate:'',
                    LicensePlateImg:"{{ url_for('static', filename='images/default/vehicle.jpg')}}",
                    GateMessage:'',
                    VehicleType:'',
                    TicketNumber:'',
                    CardNumber:'',
                    ParkingType:'',
                    GateTime:'',
                    GateTemp:'',
                },
                {
                    GateType:'Exit',
                    GateID:'',
                    GateName:'',
                    LicensePlate:'',
                    LicensePlateImg:"",
                    GateMessage:'',
                    VehicleType:'',
                    TicketNumber:'',
                    CardNumber:'',
                    ParkingType:'',
                    GateTime:'',
                    GateTemp:'',
                }
            ],
            GateBarData:{
                GateType:'',
                GateID:'',
                VehicleType: '',
                UpBarMethod:'Manual',
                LicensePlate:''
            },
            ColumnName:{
                Hourly:'時租',Monthly:'月租',Private:'專用',Car:'私家車',Moto:'電單車',GateMessage:'閘機消息',VehicleType:'車輛類型',ParkingType:'車位類型',
                TicketNumber:'時租票號',CardNumber:'月租卡號',GateTemp:'體溫檢測',Entrance:'車場入口',Exit:'車場出口',GateTime:'時間',UpBarMethod:'起杆方法',
                GateID:'閘機名稱',LicensePlate:'車牌號碼',Up:'起杆',Down:'落杆',Barrier:'閘機地感'
            },
            GateKeys:[['VehicleType','TicketNumber','CardNumber'],['GateMessage','ParkingType','GateTemp']],
            PlacesSnapshot: JSON.parse('{{PlacesSnapshot|safe}}'),
            LanesSnapshot: JSON.parse('{{LanesSnapshot|safe}}'),
        },
        methods: {
            // 加载页面数据
            load_page_data(){
                this.PlacesSnapshot.forEach(snapshot=>{this.refresh_places_status(snapshot)})
                this.LanesSnapshot.forEach(snapshot=>{this.refresh_lanes_status(snapshot)})
            },
            // 刷新车位状态
            refresh_places_status(status){
                this.Places.forEach(place=>{
                    if(place.ParkingType==status.ParkingType&&place.VehicleType==status.VehicleType){
                        place.Provide=status.Provide;place.ValidCount=status.ValidCount}
                })
            },
            // 刷新车道状态
            refresh_lanes_status(status){
                this.Lanes.forEach(lane=>{if(lane.GateType==status.GateType){for(key in lane){lane[key]=status[key]}}})
            },
            // 车位颜色
            place_icon_bg(name, valid){
                if(valid==0){return 'bg-danger'}
                switch(name){
                    case 'Hourly': return 'bg-primary'
                    case 'Monthly': return 'bg-info'
                    case 'Private': return 'bg-secondary'
                }
            },
            // 通道颜色
            lane_event_bg(lp){
                if(lp=='UNKNOWN'){return 'card-warning'}else{if(['','UNKNOWN'].includes(lp)==false){return 'card-info'}}
            },
            // 发送起杆
            send_gate_upbar(){
                axios.post("{{ url_for('charge.preview') }}", {UpBar: this.GateBarData})
                .then(response => {
                    if(response.status==200){
                        let ret = response.data
                        AppMessage.fire({icon: ret.icon, text: ret.text})
                        if(ret.icon=='success'){if($('#GateBarModal').css('display')=="block"){$("#GateBarModal").modal('toggle')}}}
                    }
                )
                .catch(function (error) {alert(error)})
            },
            // 闸杆对话框
            gatebar_control(gate_type){
                this.Lanes.forEach(lane=>{
                    if(lane.GateType==gate_type){
                        this.GateBarData.GateType = gate_type
                        this.GateBarData.GateID = lane.GateID
                        this.GateBarData.VehicleType = lane.VehicleType.toUpperCase()
                    }
                })
            }
        },
        mounted: function(){
            // 加载页面数据
            this.load_page_data()
            // socketio
            namespace = '/carpark_status';
            // Conn
            var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
            socket.auto
            // Send
            socket.on('connect', function(){
                console.log('Connect Success!');
                socket.emit('lanes_event', {'data': 'get_lanes'})
                socket.emit('places_event', {'data': 'get_places'})
            });
            // Recv
            socket.on('lanes_status', function(ret){if(ret!=null){CarParkPreview.refresh_lanes_status(ret.status)}});
            // Recv
            socket.on('places_status', function(ret){if(ret!=null){CarParkPreview.refresh_places_status(ret.status)}});
            // Close
            socket.on('disconnect', function(){console.log('Disconnect Success!')});
        },
    });
</script>
{% endblock %}
